<!DOCTYPE html>
<html>
<head>
    <title>鹿鹿泽经营指标查询</title>
    <link rel="stylesheet" href="../static/css/minghu.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
</head>
<body>
    {% include 'show_ins_info.html' %}
    <hr>
    <div>
        <div class="form-row"><h4>开始日期</h4> <input type="date" id="startDate" style="width:120px;" onchange="checkEndDate();submit();"></div>
        <div class="form-row"><h4>结束日期</h4> <input type="date" id="endDate" style="width:120px;"  onchange="checkEndDate();submit();"></div>
        <div class="form-row" style="margin-left:10px;margin-top:20px;"><button id="checkThisMonthBtn" onclick="showThisMonth();">查看本月</button></div>
        <div id="dateErr"></div>
    </div>     
    <br>
    <!-- <div style="margin-left:15px;"><button id='submit' onclick="submit();">查看运营数据</button></div> -->
    <hr>

    <div id="trialList" style="margin-bottom:30px;"></div>
 
    <div id="trialStat" style="margin-bottom:30px;"></div>
    
    <div id="trialDealedStat" style="margin-bottom:30px;"></div>

    <div id="formalList" style="margin-bottom:30px;"></div>

    <div id="formalClass" style="display:flex;flex-direction: row;">
        <div id="formalStatCg" style="margin-bottom:30px;"></div>

        <div id="formalStatLmt" style="margin-bottom:30px;"></div>
    </div>

    <div id="saleList" style="margin-bottom:30px;"></div>
    
    <div id="saleStat" style="margin-bottom:30px;"></div>

    
    
    <div id="errInfo"></div>
    </div>

    <div id="incomeChartBox" >
        <div style="display: flex;flex-direction: column;justify-content: center;align-items: center;">
            <div id="incomeTitle" style="color:rgb(95, 93, 87);font-size:18px;margin-top:20px;font-weight: bold;"></div>
            <div id="incomeTxt" style="color:#d4ad41;font-size:12px;margin-top:12px;"></div>
        </div>
        <div class="form-row" style="font-size:14px;margin-top:20px;">
            <h4 style="width:60px;">时间段</h4>
            <select id="interval" onchange="showIncomeChart()">
                <option value="30">近30天</option>
                <option value="60">近60天</option>
                <option value="90">近90天</option>
                <option value="this_month">本月</option>
                <option value="this_year">今年</option>
            </select>
        </div>   
        
        <div id="incomeCalendar" style="margin-bottom: 20px;"></div>
    </div>

    <div id="incomeByTypeChartBox" >
        <div style="display: flex;flex-direction: column;justify-content: center;align-items: center;">
            <div id="incomeByTypeTitle" style="color:rgb(95, 93, 87);font-size:18px;margin-top:20px;font-weight: bold;"></div>
            <div id="incomeByTypeTxt" style="color:rgb(95, 93, 87);font-size:12px;margin-top:12px;"></div>
        </div>
        <div class="form-row" style="font-size:14px;margin-top:20px;">
            <h4 style="width:60px;">时间段</h4>
            <select id="incomeByTypeInterval" onchange="showIncomeByType()">
                <option value="30">近30天</option>
                <option value="60">近60天</option>
                <option value="90">近90天</option>
                <option value="this_month">本月</option>
                <option value="this_year">今年</option>
                <option value="all">所有</option>
            </select>
        </div>   
        
        <div id="incomeByTypeChart" style="margin-bottom: 40px;"></div>
    </div>

    <div id="cusContributeBox" >
        <div style="display: flex;flex-direction: column;justify-content: center;align-items: center;">
            <div id="cusContributeTitle" style="color:rgb(95, 93, 87);font-size:18px;margin-top:20px;font-weight: bold;"></div>
            <div id="cusContributeTxt" style="color:rgb(95, 93, 87);font-size:12px;margin-top:12px;"></div>
        </div>
        <div class="form-row" style="font-size:14px;margin-top:20px;">
            <h4 style="width:60px;">时间段</h4>
            <select id="cusContributeInterval" onchange="showCusContribute()">
                <option value="all">所有</option>
                <option value="this_year">今年</option>
                <option value="this_month">本月</option>     
            </select>
        </div>           
        <div id="cusContributeChart" style="margin-bottom: 40px;"></div>
    </div>

    <div id="statByMonthBox" >
        <div style="display: flex;flex-direction: column;justify-content: center;align-items: center;">
            <div id="statByMonthTitle" style="color:rgb(95, 93, 87);font-size:18px;margin-top:20px;font-weight: bold;">营业收入及上课节数统计</div>
            <div id="incomeAndClsTknChart" style="margin-bottom: 40px;"></div>
        </div>        

        <div style="display: flex;flex-direction: column;justify-content: center;align-items: center;">
            <div id="statByMonthTitle" style="color:rgb(95, 93, 87);font-size:18px;margin-top:20px;font-weight: bold;">体验课 / 出单数统计</div>
            <div id="trialAndDealedChart" style="margin-bottom: 40px;"></div>
        </div>    
        
        
    </div>


    <div id="monthlyNewCusCount" style="margin-bottom:30px;">
        <div class="form-row" style="font-size:14px;margin-top:20px;margin-bottom: 20px;">
            <h4 style="width:60px;">时间段</h4>
            <select id="monthlyNewCusInterval" onchange="showMonthlyNewCusCount()">
                <option value="this_year">今年</option>
                <option value="this_month">本月</option>
                <option value="latest6months">近6个月</option>                              
                <option value="all">所有</option>
            </select>
        </div> 
    </div>

    <script src="../static/js/common.js"></script>
    <script src="../static/js/echarts.min.js"></script>
    
    <script>
        let insName;
        let insId;
        let insRole;
        let insList;

        document.addEventListener('DOMContentLoaded',function(){
            // loginCheck();

            fetch('/get_ins_list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                console.log('get ins list:',data);
                insList=data;

                 })
                .catch(error => console.error('Error:', error));
            
            const insInfo=hideInsSelectBlockAndGetInsInfo();
            insId=insInfo.sessionInsId;
            insName=insInfo.sessionInsName;
            insRole=insInfo.sessionInsRole;
            // console.log(insName)
            //教练角色不允许进入该页面，返回Index
            if(insRole==='ins'){
                window.location.replace('./index');
            }

            selectToday('startDate','date');
            selectToday('endDate','date');
            const endDate=document.getElementById('endDate');
            const eve=new Event('change');
            endDate.dispatchEvent(eve);
            document.getElementById('dateErr').textContent='';

            showIncomeChart();
            showIncomeByType();
            showCusContribute();
            showStatByMonth();
            showMonthlyNewCusCount();


        });

        function showMonthlyNewCusCount(){
            const interval=document.getElementById('monthlyNewCusInterval').value;
            const today=new Date();
            let sDate,eDate,itvStr
            if(interval==='this_month'){
                eDate=dateToString(today,'date');
                sDate=`${today.getFullYear()}-${today.getMonth()+1}-01`;
                itvStr='本月';
            }else if(interval==='this_year'){
                eDate=dateToString(today,'date');
                sDate=`${today.getFullYear()}-01-01`;
                itvStr='今年';
            }else if(interval==='all'){
                eDate=dateToString(today,'date');
                sDate=`2024-01-01`;
                itvStr='所有月份';
            }else if(interval==='latest6months'){
                const _today=new Date();
                eDate=dateToString(today,'date');
                _today.setDate(_today.getDate()-180);
                sDate=new Date(_today.getFullYear(),_today.getMonth(),1);
                sDate=`${sDate.getFullYear()}-${sDate.getMonth()+1}-01}`;
                itvStr='近6个月内';

            }else{
                eDate=dateToString(today,'date');
                sDate=today.setDate(today.getDate()-parseInt(interval));
                sDate=dateToString(sDate,'date');
                itvStr=`${interval}天内`;
            }

            // console.log(sDate,eDate)

            fetch('/new_cus_count_by_month',{
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({'sDate':sDate,'eDate':eDate})
            })
            .then(response=>response.json())
            .then(data=>{
                if(data['res']==='ok'){                   
                    console.log('monthly new cus count data:',data['data']);
                    showMonthlyCusCountChart(data['data'],itvStr);
                 
                }else{
                    
                }
            })
            .catch(error=>console.error(error))
        
        }

        function showMonthlyCusCountChart(data,interval){
            const monthlyNewCusCount=document.getElementById('monthlyNewCusCount');
            monthlyNewCusCount.style.textAlign='center';

            let chartBox=document.getElementById('monthlyNewCusChart');
            if(!chartBox){
                const title=document.createElement('div');
                title.id='chartTitle';
                title.innerHTML=`${interval}新增客户统计`;
                title.style.fontWeight='bold';
                title.style.fontSize='18px';
                title.marginTop='20px';
                monthlyNewCusCount.appendChild(title);
                chartBox=document.createElement('div');
                chartBox.id='monthlyNewCusChart';
                chartBox.style.width='380px';
                chartBox.style.height='400px';
                monthlyNewCusCount.appendChild(chartBox);
            }else{
                 
                document.getElementById('chartTitle').innerHTML=`${interval}新增客户统计`;
                if (chartBox.chartInstance) {
                echarts.dispose(chartBox.chartInstance);
    }
            }
            
  
            
            // 格式化数据
            const formattedData = data.map(item => ({
                date: `${item[0]}-${String(item[1]).padStart(2, '0')}`,
                count: item[2]
            }));

            // 提取横坐标数据（年月）和纵坐标数据（新增客户数）
            const xData = formattedData.map(item => item.date);
            const yData = formattedData.map(item => item.count);

            //找出最大值
            const thirdEle=data.map(item=>item[2]);
            const maxValue=Math.max(...thirdEle);

            // 初始化ECharts实例
            const chart = echarts.init(chartBox);

            // 配置选项
            const option = {
                title: {
                    text: ''
                },
                tooltip: {
                    trigger: 'axis'
                },
                xAxis: {
                    type: 'category',
                    data: xData,
                    axisLabel: {
                        // formatter: value => value.replace('-', '/'),
                        rotate:45,
                        fontSize:9,
                    }
                },
                yAxis: {
                    type: 'value',
                    max:maxValue+2,
                    interval:2,
                    axisLabel:{
                        fontSize:9,
                    }
                },
                series: [
                    {
                        name: '新增客户数',
                        type: 'line',
                        data: yData,
                        label:{
                            show:true,
                            position:'top',
                            formatter:(params)=>`${params.value}人`,
                        }
                    }
                ]
            };

            // 使用配置项和数据显示图表
            chart.setOption(option);
        }

        function showThisMonth(){
            const startDate=document.getElementById('startDate');
            const endDate=document.getElementById('endDate');
            const today=new Date()
            const todayStr=`${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
            const firstDayOfThisMonth=`${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-01`;           
            selectDate(firstDayOfThisMonth,'startDate','date');
            // const eve1=new Event('change');
            // startDate.dispatchEvent(eve1);

            selectDate(todayStr,'endDate','date');
            const eve2=new Event('change');
            endDate.dispatchEvent(eve2);        

            //营收情况
            const incomeInterval = document.getElementById('interval');
            if (incomeInterval) {
                incomeInterval.value = 'this_month';
                incomeInterval.dispatchEvent(new Event('change'));
            }

            const incomeByTypeInterval = document.getElementById('incomeByTypeInterval');
            if (incomeByTypeInterval) {
                incomeByTypeInterval.value = 'this_month';
                incomeByTypeInterval.dispatchEvent(new Event('change'));
            }

            

        }

        function showStatByMonth(){
            fetch('/get_business_data_by_month'
            )
            .then(response=>response.json())
            .then(data=>{
                if(data['res']==='ok'){                   
                    // console.log('stat by month data:',data['data']);
                    showIncomeAndClsCharts(data['data']);
                    showTrialDealedChart(data['data']);
                 
                }
            })
            .catch(error=>console.error(error))
        }

        function showTrialDealedChart(data){
            const trialData=data['trial_and_dealed_by_month'];
            const xAxisDataTrial=trialData.map(item=>{return item['month']});
            const yAxisTrialData=trialData.map(item=>{return item['trial_qty']});
            const notDealedData=trialData.map(item=>{return item['trial_qty']-item['dealed_qty']});
            const dealedData=trialData.map(item=>{return item['dealed_qty']});
            const dealedRate=trialData.map(item=>{return item['dealed_qty']/item['trial_qty']});

            const trialAndDealedChart=document.getElementById('trialAndDealedChart');
            const chartContainer = document.createElement('div');
            // chartContainer.classList.add('chart-wrapper');
            chartContainer.style.width='380px';
            chartContainer.style.height='290px';
            trialAndDealedChart.appendChild(chartContainer);

            const trialAndDealed = echarts.init(chartContainer);

            const showDataZoom = xAxisDataTrial.length > 5;
            const startValue = showDataZoom ? Math.max(0, xAxisDataTrial.length - 5) / xAxisDataTrial.length * 100 : 0;
            const endValue = 100;

            const option = {
                title: {
                    show:false,
                    text: '体验课/出单节数统计'
                },
                tooltip: {
                    trigger: 'axis'
                },
                grid: {
                    left: 0, // 调整左边距
                    right: 0, // 调整右边距
                    bottom: 50,
                    top: 90,
                    containLabel: true // 防止标签溢出
                },                      
                legend: {
                    data: ['未出单节数', '出单节数'],
                    top:20
                },
                xAxis: {
                    type: 'category',
                    data: xAxisDataTrial,
                    axisLabel:{
                        fontSize:10,
                        rotate:xAxisDataTrial.length>4?60:0
                    }
                },
                yAxis: [
                    {
                        type: 'value',
                        name: '节数',
                        position: 'left',
                        min: 0,
                        axisLabel: {
                            formatter: '{value} 节',
                            fontSize:10
                        }
                    }
                ],
                series: [
                    {
                        name: '未出单节数',
                        type: 'bar',
                        stack:'总数',
                        data: notDealedData,
                        label: {
                            show: true,
                            position: 'inside',
                            formatter: function (params) {
                               return params.value
                            },
                            fontSize:8
                        }                        
                    },
                    {
                        name: '出单节数',
                        type: 'bar',
                        stack:'总数',
                        data: dealedData,
                        label: {
                            show: true,
                            position: 'inside',
                            formatter: function (params) {
                                return params.value
                                
                            },
                            fontSize:8
                        },
                        markPoint: {
                            symbolSize:1,
                            data: dealedData.map((value, index) => {
                                const total = value + notDealedData[index];
                                const percent = total > 0 ? (value / total * 100).toFixed(2) : 0;
                                return {
                                    coord: [index, value + notDealedData[index]],
                                    value: percent + '%',
                                    label: {
                                        show: true,
                                        position: 'top',
                                        fontSize: 10,
                                        color: '#000'
                                    },
                                    itemStyle: {
                                        color: 'rgba(0,0,0,0)'  // 设置图标颜色为透明
                                        
                                    }
                                };
                            })
                        }
                    }                    
                ],
                dataZoom: showDataZoom ? [
                {
                    type: 'slider',
                    start: startValue,
                    end: endValue,
                    handleSize: '150%',   // 增大 handleSize 以便触摸
                    height: 20,           // 调整高度以适应移动设备
                    handleStyle: {
                        color: '#a7b7cc' // 调整 handle 的颜色以便更好地查看
                    },
                    bottom:30
                },
                {
                    type: 'inside',       // 添加 inside 类型 dataZoom 以便触摸缩放
                    start: startValue,
                    end: endValue
                }]:[]
                    
            };


            // 使用刚指定的配置项和数据显示图表。
            trialAndDealed.setOption(option);



        }
        
        function showIncomeAndClsCharts(data){
            const incomeData=data['income_by_month'];
            const clsTknData=data['cls_qty_by_month'];


            const xAxisDataIncome=incomeData.map(item=>{return item['month']});
            const yAxisDataIncome=incomeData.map(item=>{return item['real_pay']});
            const yAxisDataClsTkn=clsTknData.map(item=>{return item['cls_tkn_qty']});

            const incomeAndClsTknChart=document.getElementById('incomeAndClsTknChart');
            const chartContainer = document.createElement('div');
            // chartContainer.classList.add('chart-wrapper');
            chartContainer.style.width='390px';
            chartContainer.style.height='290px';
            incomeAndClsTknChart.appendChild(chartContainer);

            const chartIncomeAndClsTkn = echarts.init(chartContainer);
            const showDataZoom = xAxisDataIncome.length > 5;
            const startValue = showDataZoom ? Math.max(0, xAxisDataIncome.length - 5) / xAxisDataIncome.length * 100 : 0;
            const endValue = 100;

            // 指定图表的配置项和数据
            const option = {
                title: {
                    show:false,
                    text: '营业金额和上课节数统计'
                },
                tooltip: {
                    trigger: 'axis'
                },
                grid: {
                    left: 6, // 调整左边距
                    right: 6, // 调整右边距
                    bottom: 25,
                    top: '30%',
                    containLabel: true // 防止标签溢出
                },                      
                legend: {
                    show:false,
                    data: ['营业金额', '上课节数']
                },
                xAxis: {
                    type: 'category',
                    data: xAxisDataIncome,
                    axisLabel:{
                        fontSize:10,
                        rotate:xAxisDataIncome.length>4?60:0
                    }
                },
                yAxis: [
                    {
                        type: 'value',
                        name: '营业金额（元）',
                        position: 'left',
                        min: 0,
                        axisLabel: {
                            formatter: '{value}',
                            fontSize:8
                        },
                        splitLine: {
                            lineStyle: {
                                color: 'rgba(47, 71, 138, 0.3)', // 网格线颜色
                                type:'solid'
                            }
                        }
                    },
                    {
                        type: 'value',
                        name: '上课节数',
                        position: 'right',
                        min: 0,
                        axisLabel: {
                            formatter: '{value} 节'
                        },
                        axisLine: {
                            lineStyle: {
                                color: 'rgba(148, 176, 141,1)' //右边y轴的颜色
                            }
                        },
                        splitLine: {
                            lineStyle: {
                                color: 'rgba(148, 176, 141, 0.8)', // 网格线颜色
                                type:'dashed'
                            }
                        }
                    }
                ],
                series: [
                    {
                        name: '营业金额',
                        type: 'bar',
                        data: yAxisDataIncome,
                        label: {
                            show: true,
                            position: 'inside',
                            formatter: function (params) {
                                if(hasNonZeroDecimal(params.value)){
                                    return params.value === 0 ? '' : `${params.value}`;
                                }else{
                                    return params.value === 0 ? '' : `${parseInt(params.value)}`;
                                }
                                
                            },
                            fontSize:8
                        }
                    },
                    {
                        name: '上课节数',
                        type: 'line',
                        yAxisIndex: 1,
                        data: yAxisDataClsTkn,
                        label: {
                            show: true,
                            position: 'top',
                            formatter: function (params) {
                               return params.value
                                
                            },
                            fontSize:8,
                            color: 'rgba(148, 176, 141,1)'
                        }
                    }
                ],
                dataZoom: showDataZoom ? [
                {
                    type: 'slider',
                    start: startValue,
                    end: endValue,
                    handleSize: '150%',   // 增大 handleSize 以便触摸
                    height: 20,           // 调整高度以适应移动设备
                    handleStyle: {
                        color: '#a7b7cc' // 调整 handle 的颜色以便更好地查看
                    },
                    bottom:0
                },
                {
                    type: 'inside',       // 添加 inside 类型 dataZoom 以便触摸缩放
                    start: startValue,
                    end: endValue
                }]:[]
            };

            // 使用刚指定的配置项和数据显示图表。
            chartIncomeAndClsTkn.setOption(option);

        }


        function showCusContribute(){
            const interval=document.getElementById('cusContributeInterval').value;
            fetch('/get_cus_contribute_data',{
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({'interval': interval})
            })
            .then(response=>response.json())
            .then(data=>{
                if(data['res']==='ok'){                   
                    // console.log('cus contribute  data:',data['data']);
                    showCusContributeChart(data['data']);
                 
                }
            })
            .catch(error=>console.error(error))
        }

        function showCusContributeChart(data){
            const cusContributeChart=document.getElementById('cusContributeChart');
            cusContributeChart.innerHTML='';           
            const chartContainer = document.createElement('div');
            // chartContainer.classList.add('chart-wrapper');
            chartContainer.style.width='380px';
            chartContainer.style.height='200px';
            cusContributeChart.appendChild(chartContainer);

            // 初始化图表
            const chart = echarts.init(chartContainer);

            // 定义横坐标数据
            const xAxisData=data.map(value=>value['cus_name']);
            // 定义总数数据
            const YAxisData=data.map(value=>value['total_pay']);

            const total=data[0]['all_total_real_pay'];


            // 配置图表选项
            const titleStr=`会员对店贡献度`;
            const options = {
                // title: {
                //     text: titleStr,
                //     textStyle: {
                //         color: '#a479b8', // 标题颜色
                //         fontSize: 14 // 标题字体大小
                //     }
                // },
                xAxis: {
                    type: 'category',
                    name:'会员',
                    data: xAxisData,
                    axisLabel: {
                        //color: '#bd8333', // 坐标轴文字颜色
                        fontSize: 10, // 坐标轴文字大小
                        rotate:60
                    }
                },
                yAxis: [
                    {
                        type: 'value',
                        name: '购课金额',
                        position: 'left',
                        axisLabel: {
                            //color: 'blue', // 坐标轴文字颜色
                            fontSize: 10, // 坐标轴文字大小
                        },
                        nameTextStyle: {
                            padding: [0, 0, 10,0], // 调整这个值来改变名称与坐标轴的距离
                            fontSize: 12,
                            color: '#333'
                        }
                    }
                ],
                series: [
                    {
                        name: '购课金额',
                        type: 'bar',
                        yAxisIndex: 0,
                        data: YAxisData,
                        itemStyle: {
                            color: '#6783f5' // 设置柱状图的颜色
                        },
                        label: {
                            show: true,
                            position: 'top',
                            distance:2,
                            formatter: function (params) {
                                if(hasNonZeroDecimal(params.value)){
                                    return params.value === 0 ? '' : `${params.value}\n（${(params.value*100/total).toFixed(2)}%）`;
                                }else{
                                    return params.value === 0 ? '' : `${parseInt(params.value)}\n（${(params.value*100/total).toFixed(2)}%）`;
                                }
                                
                            },
                            fontSize:8
                        }
                    }
                ]
            };

            // 使用配置项生成图表
            chart.setOption(options);
            const cusContributeTitle=document.getElementById('cusContributeTitle');
            const cusContributeTxt=document.getElementById('cusContributeTxt');
            cusContributeTitle.innerHTML='会员对店贡献度（前十位）';
            cusContributeTxt.innerHTML=`<div style="text-align:center;"><p style="margin:2px;">（单位：元）</p><p style="margin:2px;">总贡献金额：${hasNonZeroDecimal(total)?total:parseInt(total)} 元</p></div>`;
            cusContributeChart.appendChild(chartContainer);


        }


        function showIncomeByType(){
            const interval=document.getElementById('incomeByTypeInterval').value;
            fetch('/get_income_stat_by_type',{
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({'interval': interval})
            })
            .then(response=>response.json())
            .then(data=>{
                if(data['res']==='ok'){                   
                    // console.log('income by type data:',data['data']);
                    showIncomeByTypeChart(data['data']);
                 
                }
            })
            .catch(error=>console.error(error))
        }

        function showIncomeByTypeChart(data) {
            const incomeByTypeChart = document.getElementById('incomeByTypeChart');
            incomeByTypeChart.innerHTML = '';
            const chartContainer = document.createElement('div');
            chartContainer.style.width = '370px';
            chartContainer.style.height = '200px';

            // 教练去重名单
            let insA = [];
            data.forEach(dat => {
                if (!insA.includes(dat['ins_id'])) {
                    insA.push(dat['ins_id']);
                }
            });
            insA.sort((a, b) => parseInt(a[0].slice(5)) - parseInt(b[0].slice(5)));

            let insArr = [];
            insA.forEach(insId => {
                data.forEach(item => {
                    if (insId === item['ins_id'] && !insArr.includes(item['ins_name'])) {
                        insArr.push(item['ins_name']);
                    }
                });
            });

            // 新单、续课单数
            let insNewQty = [];
            let insRewNewQty = [];
            insArr.forEach(ins => {
                let qtyNew = 0;
                let qtyRenew = 0;
                data.forEach(dat => {
                    if (dat['ins_name'] === ins && dat['income_type'] === '新单') {
                        qtyNew += parseInt(dat['buy_qty']);
                    }

                    if (dat['ins_name'] === ins && dat['income_type'] === '续课') {
                        qtyRenew += parseInt(dat['buy_qty']);
                    }
                });
                insNewQty.push(qtyNew);
                insRewNewQty.push(qtyRenew);
            });

            // 新单、续课金额
            let insNewAmt = [];
            let insRewNewAmt = [];
            insArr.forEach(ins => {
                let amtNew = 0;
                let amtRenew = 0;
                data.forEach(dat => {
                    if (dat['ins_name'] === ins && dat['income_type'] === '新单') {
                        amtNew += parseInt(dat['real_pay']);
                    }

                    if (dat['ins_name'] === ins && dat['income_type'] === '续课') {
                        amtRenew += parseInt(dat['real_pay']);
                    }
                });
                insNewAmt.push(amtNew);
                insRewNewAmt.push(amtRenew);
            });

            // 初始化图表
            const chart = echarts.init(chartContainer);

            // 数据
            const incomeByTypeData = {
                coaches: insArr,
                newCourses: insNewAmt,
                renewCourses: insRewNewAmt
            };

            const totals = incomeByTypeData.coaches.map((_, index) => {
                return incomeByTypeData.newCourses[index] + incomeByTypeData.renewCourses[index];
            });

            const totalAll = totals.reduce((sum, current) => sum + current, 0);

            // 配置项
            const option = {
                title: {
                    show: false,
                    text: '教练售课新单/续课金额条形图'
                },
                tooltip: {
                    show: false,
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                legend: {
                    top: 24,
                    data: ['新单', '续课']
                },
                grid: {
                    left: '3%',
                    right: '8%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'value',
                    axisLabel: {
                        fontSize: 8
                    }
                },
                yAxis: {
                    type: 'category',
                    data: incomeByTypeData.coaches
                },
                series: [
                    {
                        name: '新单',
                        type: 'bar',
                        stack: '总量',
                        label: {
                            show: true,
                            position: 'inside',
                            formatter: function (p) {
                                let total = totals[p.dataIndex];
                                let str;
                                if (p.value === 0) {
                                    str = '';
                                } else {
                                    if (hasNonZeroDecimal(parseFloat(p.value * 100 / total).toFixed(2))) {
                                        str = `${p.value}\n （${(p.value * 100 / total).toFixed(2)}%）`;
                                    } else {
                                        str = `${p.value}\n （${(p.value * 100 / total).toFixed(0)}%）`;
                                    }
                                }
                                return str;
                            },
                            textStyle: {
                                fontSize: 8,
                                align: 'center',
                            }
                        },
                        data: incomeByTypeData.newCourses
                    },
                    {
                        name: '续课',
                        type: 'bar',
                        stack: '总量',
                        label: {
                            show: true,
                            position: 'inside',
                            formatter: function (p) {
                                let total = totals[p.dataIndex];
                                let str;
                                if (p.value === 0) {
                                    str = '';
                                } else {
                                    if (hasNonZeroDecimal(parseFloat(p.value * 100 / total).toFixed(2))) {
                                        str = `${p.value}\n （${(p.value * 100 / total).toFixed(2)}%）`;
                                    } else {
                                        str = `${p.value}\n （${(p.value * 100 / total).toFixed(0)}%）`;
                                    }
                                }
                                return str;
                            },
                            textStyle: {
                                fontSize: 8,
                                align: 'center',
                            }
                        },
                        data: incomeByTypeData.renewCourses
                    },
                    // 新增系列用于显示总业绩及其占比
                    {
                        name: '总业绩',
                        type: 'bar',
                        stack: '总量',
                        label: {
                            show: true,
                            position: 'right', // 在条形图右侧显示
                            formatter: function (p) {
                                let total = totals[p.dataIndex];
                                let percentage = ((total / totalAll) * 100).toFixed(2);
                                return `  共${total}元\n (${percentage}%)`;
                            },
                            textStyle: {
                                fontSize: 7,
                                align: 'left',
                                color:'#c41b59',
                            }
                        },
                        data: totals.map(() => 0), // 使用0确保不影响原有堆叠结构
                        itemStyle: {
                            color: 'transparent' // 使其不可见
                        }
                    }
                ]
            };

            // 使用刚指定的配置项和数据显示图表。
            chart.setOption(option);
            const incomeByTypeTitle = document.getElementById('incomeByTypeTitle');
            const incomeByTypeTxt = document.getElementById('incomeByTypeTxt');
            incomeByTypeTitle.innerHTML = '教练业绩按收入类型分类';
            incomeByTypeTxt.innerHTML = '（单位：元）'
            incomeByTypeChart.append(chartContainer);
        }


    
        function showIncomeChart(){
            const interval=document.getElementById('interval').value;
            fetch('/get_income_calendar_data',{
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({'interval': interval})
            })
            .then(response=>response.json())
            .then(data=>{
                if(data['res']==='ok'){                   
                    // console.log('income calendar data:',data['data']['income_calendar_stat']);
                    showIncomeCalendar(data['data']['income_calendar_stat']);
                }
            })
            .catch(error=>console.error(error))
        }


        function createPieces(maxValue, interval) {
                let pieces = [{ value: 0, color: '#fafffe' }];
                if(maxValue<=2000){
                    pieces.push({min: 1, max: 1000,color:'#fcfcc7'});
                    pieces.push({min: 1000, max: 2000,color:'#fff240'});                    
                }else{
                    pieces.push({min: 1, max: 1000,color:'#fcfcc7'});
                    pieces.push({min: 1000, max: 2000,color:'#fff240'});     
                    for(let i=2000;i<maxValue;i+=interval){
                        pieces.push({min: i, max: i+interval});
                    }
                }

                return pieces;
            }
        

        function showIncomeCalendar(spotDates) {

            const incomeTitle=document.getElementById('incomeTitle');
            const incomeTxt=document.getElementById('incomeTxt');
            incomeTitle.innerHTML='';
            incomeTxt.innerHTML='';

            const interval=document.getElementById('interval').value;
            let startDate;
            let endDate;
            if (interval === 'this_year') {
                const today = new Date();                
                startDate = new Date(today.getFullYear() + '-01-01');
                endDate = new Date();             
            }else if(interval === 'this_month'){
                const today = new Date();                
                startDate = new Date(today.getFullYear() + '-'+(today.getMonth()+1)+'-01');
                endDate = new Date();          
            }
             else {
                startDate = new Date();
                startDate.setDate(startDate.getDate() - interval+1);//不带那一天
                endDate = new Date();
                // console.log(startDate,endDate)
            }
            
            let currentDate = new Date(startDate);          
            const spotDatesDic = Object.fromEntries(spotDates.map(([date, value]) => [dateToString(date,'date'), value]));

            let result=[];
            while (currentDate <= endDate) {
                // currentDate.setUTCHours(0,0,0,0)
                const dateStr = toBeijingTimeString(currentDate);
                const isSpot = Object.keys(spotDatesDic).includes(dateStr);      
                result.push([dateStr, isSpot ? spotDatesDic[dateStr] : "0"]);
                currentDate.setDate(currentDate.getDate() + 1);
            }

            // console.log('spotDates:',spotDatesDic,'\nresult:',result,'\nstart date:',startDate,'\nend date:',endDate);

            try{
                myChart.dispose();
            }catch(error){
                
            }

            const mainContainer = document.getElementById('incomeCalendar');
            mainContainer.innerHTML='';
            
            const containerWidth = mainContainer.offsetWidth;

  

            let titleStr
            let gap;
            switch (interval) {
                case '30':
                    titleStr = `最近30天营收情况`;
                    gap=120;
                    break;
                case '60':
                    titleStr = `最近60天营收情况`;
                    gap=130;
                    break;
                case '90':
                    titleStr = `最近90天营收情况`;
                    gap=130;;
                    break;
                case 'this_month':
                    titleStr = `${startDate.getMonth()+1}月营收情况`;
                    gap=130;
                    break;
                case 'this_year':
                    titleStr = `${startDate.getFullYear()}年营收情况`;
                    gap=100;
                    break;
            }

            let sumIncome = 0;
            Object.entries(spotDatesDic).forEach(([key, value]) => {
                sumIncome += parseFloat(value);
            });

            incomeTitle.innerHTML=`${titleStr}`;
            incomeTxt.innerHTML=`营收 ${sumIncome.toFixed(2)}元`;


            const incomeMax=spotDates.reduce((max, row) => {
                    // 将第二个元素转换为数值类型
                    const value = parseFloat(row[1]);                    
                    // 返回当前累积的最大值和当前元素值中的较大者
                    return value > max ? value : max;
                }, 0);

            const visualMapMax=incomeMax>1000?Math.ceil(incomeMax/1000)*1000:incomeMax;
            
            const numDays = 7;
            let numWeeks;
            if(interval==='this_year'){
                // numWeeks=52
                const oneDay = 24 * 60 * 60 * 1000;
                const diffDays = Math.round(Math.abs((endDate - startDate) / oneDay));
                numWeeks = Math.ceil(diffDays / 7);
            }else{
                const oneDay = 24 * 60 * 60 * 1000;
                const diffDays = Math.round(Math.abs((endDate - startDate) / oneDay));
                numWeeks = Math.ceil(diffDays / 7);
            }            

            const cellSize = Math.floor(containerWidth / numDays);
            mainContainer.style.height = (cellSize*0.88 * numWeeks)+gap + 'px';

            // console.log(numWeeks,cellSize,mainContainer.style.height)

            const pieces = createPieces(visualMapMax, 2000);
            // console.log(visualMapMax,pieces)           

            myChart = echarts.init(mainContainer);
            // startDate.setDate(startDate.getDate()+1);
            const option = {
                title: {
                    show:false,
                    top: 0,
                    left: 'center',
                    text: titleStr
                },
                tooltip: {
                    show:true,
                    position: 'top',
                    formatter: function (p) {
                        var format = echarts.format.formatTime('yyyy-MM-dd', p.data[0]);
                        return p.data[1]==="0"?":-)":p.data[1]; //显示金额
                    }
                },
                visualMap: {
                    min:1,
                    max:visualMapMax,
                    orient: 'horizontal',
                    left: 'center',
                    top: 20,
                    itemWidth: 8, // 设置图示宽度
                    itemHeight: 8, // 设置图示高度
                    type: 'piecewise',
                    // pieces: [
                    //     {value: 0, color: '#fafffe'}, // 定义0的颜色
                    //     {min: 1, max: 1000}, // 定义特定值10的颜色
                    //     {min: 1000, max: 2000},             // 范围1到9的值使用渐变色
                    //     {min: 2000, max: 3000},
                    //     {min: 3000, max: visualMapMax}  // 范围11到最大值使用渐变色
                    // ],
                    pieces:pieces,
                    inRange:{color: ['#ffffff','#ffff24','#ffc354', '#ff2626']},
                    textStyle: {
                    color: '#75807f',
                    lineHeight: 20, // 调整行高
                    fontSize: 8
                    }
                },
                calendar: {
                    orient: 'vertical',
                    top: 90,
                    left: 50,
                    right: 20,
                    cellSize: [cellSize, cellSize*0.8],
                    range: [dateToString(startDate,'date'), dateToString(endDate,'date')],
                    itemStyle: {
                        borderWidth: 0.5
                    },
                    splitLine: {
                        show: true,
                        lineStyle: {
                            color: '#ccc',
                            type: 'solid'
                        }
                    },
                    dayLabel: {
                        firstDay: 1,
                        nameMap: 'cn',
                        margin:8,
                        fontSize: 13,
                        color:'#7d7972'
                    },
                    monthLabel: {
                        show: true,
                        nameMap: 'cn',
                        margin: 15,
                        fontSize: 16,
                        color:'#7d7972'
                    },
                    yearLabel: {
                        show: false
                    }
                },
                series: {
                    type: 'heatmap',
                    coordinateSystem: 'calendar',
                    data: result,
                    label: {
                        show: true,
                        formatter: function(p) {
                            return echarts.format.formatTime('d', p.data[0]);
                        },
                        textStyle: {
                            color: '#555555'
                        }
                    }
                }
            };

            myChart.setOption(option);
        }

        function showSaleStat(data,saleCount){
            // console.log('sale data:',data,'\nsale count data:',saleCount);
            const formalStat=document.getElementById('saleStat');
            formalStat.textContent='';

            const tag=document.createElement('div');
            tag.classList.add('div-tag');
            tag.textContent='销售统计';
            tag.style.backgroundColor='#3755ad';
            tag.style.color='#ffffff';
            formalStat.appendChild(tag);
            if(data.length>0){
                // 创建表格元素
                const table = document.createElement('table');

                // 创建表头行
                const headerRow = table.insertRow();
                headerRow.classList.add('header-row-business');
                //headerRow.style.fontSize='12px';
                for (const header of ['教练','常规课程金额 / 单数','限时课程金额 / 单数','总金额 / 单数']) {
                const cell = headerRow.insertCell();
                cell.textContent = header;
                }

                let total=[]
                total[0]='total_realpay';
                total[1]='合计';
                total[2]=0,
                total[3]=0;
                total[4]=0;
                let countQty=[]
                countQty[0]='total_count';
                countQty[1]='合计';
                countQty[2]=0,
                countQty[3]=0;
                countQty[4]=0;
                for (let i = 0; i < Object.keys(data).length; i++) {
                    total[2]=total[2]+parseFloat(data[i][2]);
                    total[3]=total[3]+parseFloat(data[i][3]);
                    total[4]=total[4]+parseFloat(data[i][4]);
                    countQty[2]=countQty[2]+saleCount[i][2];
                    countQty[3]=countQty[3]+saleCount[i][3];
                    countQty[4]=countQty[4]+saleCount[i][4];
                }

                for (let i = 0; i < Object.keys(data).length+1; i++) {
                    const row = table.insertRow(); 
                    if(i<Object.keys(data).length){
                        for (let j=1;j<data[0].length;j++) {
                            const cell = row.insertCell();         
                            if(j==1){
                                cell.innerHTML = `${data[i][j]}`; 
                            }else{
                                cell.innerHTML = `<span style="color:#c23a30;">${data[i][j]}</span> / <span style="color:#36a3ad;">${saleCount[i][j]}</span>`;      
                            }            
                                                  
                        }  
                    }else{
                        for(let j=1;j<data[0].length;j++){
                            const cell = row.insertCell();   
                            if(j===1){
                                cell.innerHTML = `${total[j]}`;  
                            }else{
                                cell.innerHTML = `<span style="color:#c23a30;">${parseFloat(total[j]).toFixed(2)}</span> / <span style="color:#36a3ad;">${countQty[j]} </span>`; 
                            }                     
                            
                        }
                    }             
                }
 


                formalStat.appendChild(table)
                formalStat.classList.add('table-trial');                

            }else{
                formalStat.textContent='';
            }
            const hr=document.createElement('hr');
            const br=document.createElement('br');
            // formalStat.appendChild(hr);
            formalStat.appendChild(br);

        
        }


        function showFormalStatCg(data){            
            const formalStat=document.getElementById('formalStatCg');
            formalStat.textContent='';

            const tag=document.createElement('div');
            tag.classList.add('div-tag');
            tag.textContent='常规课程上课统计';
            tag.style.backgroundColor='#db5123';
            tag.style.color='#ffffff';
            formalStat.appendChild(tag);


            if(data.length>0){
                // 创建表格元素
                const table = document.createElement('table');

                // 创建表头行
                const headerRow = table.insertRow();
                headerRow.classList.add('header-row-business');
                //headerRow.style.fontSize='12px';
                for (const header of ['教练','常规课程节数']) {
                const cell = headerRow.insertCell();
                cell.textContent = header;
                }

                for (let i = 0; i < Object.keys(data).length; i++) {
                const row = table.insertRow();                
                    for (let j=1;j<data[0].length;j++) {
                        const cell = row.insertCell();                        
                            cell.textContent = data[i][j];                 
                                              
                    }
                }
                formalStat.appendChild(table)
                formalStat.classList.add('table-trial');    
                
                const hr=document.createElement('hr');
                const br=document.createElement('br');
                // formalStat.appendChild(hr);
                formalStat.appendChild(br);

            }else{
                formalStat.textContent='';
            }
            
        
        }

        function showFormalStatLmt(data){
            const formalStat=document.getElementById('formalStatLmt');
            formalStat.textContent='';

            const tag=document.createElement('div');
            tag.classList.add('div-tag');
            tag.textContent='限时课程上课统计';
            tag.style.backgroundColor='#db5123';
            tag.style.color='#ffffff';
            formalStat.appendChild(tag);

            if(data.length>0){
                // 创建表格元素
                const table = document.createElement('table');

                // 创建表头行
                const headerRow = table.insertRow();
                headerRow.classList.add('header-row-business');
                //headerRow.style.fontSize='12px';
                for (const header of ['教练','限时课程节数']) {
                const cell = headerRow.insertCell();
                cell.textContent = header;
                }

                for (let i = 0; i < Object.keys(data).length; i++) {
                const row = table.insertRow();                
                    for (let j=1;j<data[0].length;j++) {
                        const cell = row.insertCell();                        
                            cell.textContent = data[i][j];                 
                                              
                    }
                }
                formalStat.appendChild(table)
                formalStat.classList.add('table-trial');   

                const hr=document.createElement('hr');
                const br=document.createElement('br');
                // formalStat.appendChild(hr);
                formalStat.appendChild(br);             

            }else{
                formalStat.textContent='';
            }
        
        }


        function showFormalList(data){
            // console.log('formal class list:',data);
            const formalList=document.getElementById('formalList');
            formalList.textContent='';
            const tag=document.createElement('div');
            tag.classList.add('div-tag');
            tag.textContent='正式课上课清单';
            tag.style.backgroundColor='#db5123';
            tag.style.color='#ffffff';
            formalList.appendChild(tag);


            if(data.length>0){
                // 创建表格元素
                const table = document.createElement('table');
                const buttonDiv=document.createElement('div');
                buttonDiv.id='buttonBox';


                // 创建表头行
                const headerRow = table.insertRow();
                headerRow.classList.add('header-row-business');
                //headerRow.style.fontSize='12px';
                for (const header of ['序号','教练','课程类型','课程名称','会员姓名/昵称','上课时间']) {
                const cell = headerRow.insertCell();
                cell.textContent = header;
                }

                for (let i = 0; i < Object.keys(data).length; i++) {
                const row = table.insertRow();
                row.id='formalRowId-'+i
                    for (let j=1;j<data[0].length+2;j++) {
                        const cell = row.insertCell();
                        if(j===1){
                            cell.textContent = i+1;  
                        }else{
                            if(j===6){
                                cell.innerHTML = `<span style="font-size:10px;">${dateToStringGmt(data[i][j-2],'dateHour')}</span>`;                
                            }else{
                                cell.innerHTML = `${data[i][j-2]}`                  
                            }
                        }
                          
                    }
                }
                
                // trialList.appendChild(buttonDiv)
                formalList.appendChild(table)

                formalList.classList.add('table-trial');

                //大于1条的折叠，最留最近一条记录
                for(i=0;i<Object.keys(data).length;i++){
                    if(i!==Object.keys(data).length-1){
                        const  trialRow=document.getElementById(`formalRowId-${i}`);
                        trialRow.style.display='none';
                    }                    
                }
                
                if(Object.keys(data).length>1){
                    const firstDiv=document.getElementById('formalRowId-0');
                    const hideButton=document.createElement('button');
                    hideButton.textContent=`显示全部${data.length}条正式课清单`;
                    hideButton.addEventListener('click',function(){
                        if( hideButton.textContent===`显示全部${data.length}条正式课清单`){
                            hideButton.textContent='只显示一条正式课记录';
                        }else{
                            hideButton.textContent=`显示全部${data.length}条正式课清单`;
                        }
                       
                        for(i=0;i<Object.keys(data).length-1;i++){
                            const  trialRow=document.getElementById(`formalRowId-${i}`);
                           
                            if(window.getComputedStyle(trialRow).getPropertyValue('display')=='none'){
                                trialRow.style.display='table-row';
                            }else{
                                trialRow.style.display='none';
                            }
                        }
                            
                    })
                    
             
                    formalList.appendChild(hideButton);

                }
                const hr=document.createElement('hr');
                const br=document.createElement('br');
                // formalList.appendChild(hr);
                formalList.appendChild(br);


            }else{
                formalList.textContent='';
            }
        }

        function showTrialDealedStat(data){
            // console.log('trial stat data:',data)
            const trialDealedStat=document.getElementById('trialDealedStat');
            trialDealedStat.textContent='';
            const tag=document.createElement('div');
            tag.classList.add('div-tag');
            tag.textContent='体验课及出单统计';
            tag.style.backgroundColor='#299e42';
            tag.style.color='#ffffff';            
            trialDealedStat.appendChild(tag);

            //有data且合计的体验课数>0
            if(data && data[0][2]>0){
                const dealedDiv=document.createElement('div');
                dealedDiv.style.marginTop='40px;'
                // dealedDiv.innerHTML=`体验课共<span>${data[0]}节，出单<span>${data[1]}节，出单率<span>${(parseFloat(data[2]*100).toFixed(2))}% 。</span>`
                const table=document.createElement('table');
                const headerRow = table.insertRow();
                headerRow.classList.add('header-row-business');
                for (const header of ['教练姓名','体验课节数','出单节数','出单率']) {
                    const cell = headerRow.insertCell();
                    cell.textContent = header;
                }
                
                for(i=0;i<data.length;i++){
                    const row=table.insertRow();
                    for(j=1;j<data[i].length;j++){
                        const cell=row.insertCell();
                        if(j===4){
                            if(parseFloat(data[i][j])===1){
                                cell.textContent=(parseFloat(data[i][j])*100).toFixed(0)+'%';
                            }else{
                                cell.textContent=(parseFloat(data[i][j])*100).toFixed(2)+'%';
                            }
                            
                        }else{
                            cell.textContent=data[i][j];
                        }
                        
                    }
                }

                dealedDiv.appendChild(table);
                dealedDiv.classList.add('table-trial');


                trialDealedStat.appendChild(dealedDiv);
                const hr=document.createElement('hr');
                const br=document.createElement('br');
                // trialDealedStat.appendChild(hr);
                trialDealedStat.appendChild(br);

            }else{
                trialDealedStat.textContent='';
            }
        }

        function showTrialStat(data){
            const trialStat=document.getElementById('trialStat');
            trialStat.textContent='';
            const tag=document.createElement('div');
            tag.classList.add('div-tag');
            tag.textContent='体验课统计';
            tag.style.backgroundColor='#a1105d';
            tag.style.color='#ffffff';
            trialStat.appendChild(tag);


            if(data.length>0){
                // 创建表格元素
                const table = document.createElement('table');

                // 创建表头行
                const headerRow = table.insertRow();
                headerRow.classList.add('header-row-business');
                //headerRow.style.fontSize='12px';
                for (const header of ['教练','体验课节数']) {
                const cell = headerRow.insertCell();
                cell.textContent = header;
                }

                for (let i = 0; i < Object.keys(data).length; i++) {
                const row = table.insertRow();                
                    for (let j=1;j<data[0].length;j++) {
                        const cell = row.insertCell();                        
                            cell.textContent = data[i][j];                 
                                              
                    }
                }
                trialStat.appendChild(table)
                trialStat.classList.add('table-trial');   
                
                const hr=document.createElement('hr');
                const br=document.createElement('br');
                // trialStat.appendChild(hr);
                trialStat.appendChild(br);

            }else{
                trialStat.textContent='';
            }
        
        }

        function showTrialList(data){
            const trialList=document.getElementById('trialList');
            trialList.textContent='';
            const tag=document.createElement('div');
            tag.classList.add('div-tag');
            tag.textContent='体验课清单';
            tag.style.backgroundColor='#299e42';
            tag.style.color='#ffffff';
            trialList.appendChild(tag);


            if(data.length>0){
                // 创建表格元素
                const table = document.createElement('table');
                const buttonDiv=document.createElement('div');
                buttonDiv.id='buttonBox';


                // 创建表头行
                const headerRow = table.insertRow();
                headerRow.classList.add('header-row-business');
                //headerRow.style.fontSize='12px';
                for (const header of ['序号','教练','体验课日期','体验客户','体验客户来源','出单']) {
                const cell = headerRow.insertCell();
                cell.textContent = header;
                }

                for (let i = 0; i < Object.keys(data).length; i++) {
                const row = table.insertRow();
                row.id='trialRowId-'+i
                    for (let j=0;j<data[0].length;j++) {
                        const cell = row.insertCell();
                        if(j===0){
                            cell.textContent = i+1;  
                        }else{
                            if(j===2){
                                cell.textContent = dateToStringGmt(data[i][j],'date');                
                            }else{
                                cell.textContent = data[i][j];                  
                            }
                        }
                        
                          
                    }
                }
                
                // trialList.appendChild(buttonDiv)
                trialList.appendChild(table)

                trialList.classList.add('table-trial');

                //大于1条的折叠，最留最近一条记录
                for(i=0;i<Object.keys(data).length;i++){
                    if(i!==Object.keys(data).length-1){
                        const  trialRow=document.getElementById(`trialRowId-${i}`);
                        trialRow.style.display='none';
                    }                    
                }
                
                if(Object.keys(data).length>1){
                    const firstDiv=document.getElementById('trialRowId-0');
                    const hideButton=document.createElement('button');
                    hideButton.textContent=`显示全部${data.length}条体验课清单`;
                    hideButton.addEventListener('click',function(){
                        if( hideButton.textContent===`显示全部${data.length}条体验课清单`){
                            hideButton.textContent='只显示一条体验课记录';
                        }else{
                            hideButton.textContent=`显示全部${data.length}条体验课清单`;
                        }
                       
                        for(i=0;i<Object.keys(data).length-1;i++){
                            const  trialRow=document.getElementById(`trialRowId-${i}`);
                           
                            if(window.getComputedStyle(trialRow).getPropertyValue('display')=='none'){
                                trialRow.style.display='table-row';
                            }else{
                                trialRow.style.display='none';
                            }
                        }
                            
                    })
                    
             
                    trialList.appendChild(hideButton);
                    const hr=document.createElement('hr');
                    const br=document.createElement('br');
                    // trialList.appendChild(hr);
                    trialList.appendChild(br);
                }

            }else{
                trialList.textContent='';
            }
        }

        function showSaleList(data){
            console.log('show sale list:',data);
            const saleList=document.getElementById('saleList');
            saleList.textContent='';
            const tag=document.createElement('div');
            tag.classList.add('div-tag');
            tag.textContent='销售清单';
            tag.style.backgroundColor='#3755ad';
            tag.style.color='#ffffff';
            saleList.appendChild(tag);


            if(data.length>0){
                // 创建表格元素
                const table = document.createElement('table');
                const buttonDiv=document.createElement('div');
                buttonDiv.id='buttonBox';


                // 创建表头行
                //brt.buy_date,CONCAT(brt.cus_id,brt.cus_name) AS cus_id_name,brt.buy_type,CONCAT(brt.buy_num,'/',brt.buy_cls_days) as buy_num_days,brt.real_pay,ct.cashier_name FROM buy_rec_table brt
                const headerRow = table.insertRow();
                headerRow.classList.add('header-row-business');
                headerRow.style.fontSize='8px';
                //headerRow.style.fontSize='12px';
                for (const header of ['序号','购课日期','客户姓名','购课类型','购课节数/天数','购课金额','出单人姓名']) {
                const cell = headerRow.insertCell();
                cell.textContent = header;
                }

                for (let i = 0; i < Object.keys(data).length; i++) {
                const row = table.insertRow();
                row.id='saleListRow-'+i
                    for (let j=0;j<data[0].length+1;j++) {
                        const cell = row.insertCell();
                        if(j===0){
                            cell.textContent = i+1;  
                        }else{
                            if(j===1){
                                cell.textContent = dateToStringGmt(data[i][j-1],'dateShortSlash');                
                            }else if(j===3){
                                let typeColor='#000000';
                                if(data[i][j-1].split('/')[0].includes('常规')){
                                    typeColor='#5bba4c';
                                }else if(data[i][j-1].split('/')[0].includes('限时')){
                                    typeColor='#b8472a';
                                }
                                cell.innerHTML=`<span style='font-size:8px;font-weight:bold;color:${typeColor};'>${data[i][j-1].split('/')[0]}</span><br><span style='font-size:8px;font-weight:bold;color:#407ec9;'>${data[i][j-1].split('/')[1]}</span>`;
                            }else if(j===5){
                                cell.textContent = hasNonZeroDecimal(data[i][j-1])?data[i][j-1]:parseInt(data[i][j-1]);       
                            }else{
                                cell.textContent = data[i][j-1];                  
                            }
                        }
                        
                          
                    }
                }
                
                // trialList.appendChild(buttonDiv)
                saleList.appendChild(table)

                saleList.classList.add('table-sale');

                //大于1条的折叠，最留最近一条记录
                for(i=0;i<Object.keys(data).length;i++){
                    if(i!==Object.keys(data).length-1){
                        const  saleListRow=document.getElementById(`saleListRow-${i}`);
                        saleListRow.style.display='none';
                    }                    
                }
                
                if(Object.keys(data).length>1){
                    const firstDiv=document.getElementById('saleListRow-0');
                    const hideButton=document.createElement('button');
                    hideButton.textContent=`显示全部${data.length}条购课清单`;
                    hideButton.addEventListener('click',function(){
                        if( hideButton.textContent===`显示全部${data.length}条购课清单`){
                            hideButton.textContent='只显示一条购课记录';
                        }else{
                            hideButton.textContent=`显示全部${data.length}条购课清单`;
                        }
                       
                        for(i=0;i<Object.keys(data).length-1;i++){
                            const  saleListRow=document.getElementById(`saleListRow-${i}`);
                           
                            if(window.getComputedStyle(saleListRow).getPropertyValue('display')=='none'){
                                saleListRow.style.display='table-row';
                            }else{
                                saleListRow.style.display='none';
                            }
                        }
                            
                    })
                    
             
                    saleList.appendChild(hideButton);
                    const hr=document.createElement('hr');
                    const br=document.createElement('br');
                    // trialList.appendChild(hr);
                    saleList.appendChild(br);
                }

            }else{
                saleList.textContent='';
            }
        }


        function checkEndDate(){
            const endDate=new Date(document.getElementById('endDate').value);
            const startDate=new Date(document.getElementById('startDate').value);
            if(endDate<startDate){
                selectDate(document.getElementById('startDate').value,'endDate','date');
                document.getElementById('dateErr').textContent='结束日不能早于起始日，已改为与起始日同一天。';
            }else{
                document.getElementById('dateErr').textContent='';
            }
        }



        function submit(){
            const startDate=document.getElementById('startDate').value;
            const endDate=document.getElementById('endDate').value;

            fetch('/get_business_data',{
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body:JSON.stringify({'start_date':startDate,'end_date':endDate})
                })
            .then(response => response.json())
            .then(data => {
                // console.log('business data:',data);
                if(data['formal_stat_cg'].length>0 || data['formal_stat_lmt'].length>0){
                    const formalClass=document.getElementById('formalClass');
                    formalClass.style.display='flex';
                }else{
                    const formalClass=document.getElementById('formalClass');
                    formalClass.style.display='none';
                }

                showTrialList(data['trial_class_list']);
                // showTrialStat(data['trial_stat']);
                showTrialDealedStat(data['trial_dealed_stat'])
                showFormalList(data['formal_class_list']);
                showFormalStatCg(data['formal_stat_cg']);
                showFormalStatLmt(data['formal_stat_lmt']);                
                showSaleStat(data['sale_stat'],data['sale_count_stat']);
                showSaleList(data['sale_list']);


            })
            .catch(error => console.error('Error:', error));
        }
      

    </script>
  
</body>
</html>
